package edu.thu.studio.ormdesigner.editor.command;

import edu.thu.studio.ormdesigner.common.AbstractCommand;
import edu.thu.studio.ormdesigner.model.diagram.link.Link;
import edu.thu.studio.ormdesigner.model.diagram.node.Node;
import edu.thu.studio.ormdesigner.model.diagram.node.TableNode;
import edu.thu.studio.ormdesigner.util.Utils;

public class CreateLinkCommand extends AbstractCommand {

	protected Node source;

	protected Node target;

	private Link link;

	public CreateLinkCommand(Node source) {
		this.source = source;
	}

	public void setSource(Node source) {
		this.source = source;
	}

	public void setTarget(Node target) {
		this.target = target;
	}

	@Override
	public boolean canExecute() {
		if (super.canExecute()) {
			if (!source.equals(target)) {
				// 只有表才能创建关系
				if (source instanceof TableNode && target instanceof TableNode) {
//					TableNode sourceNode = (TableNode) source;
//					boolean hasLinked = Utils.getDiagram(sourceNode)
//							.getDiagram().getLinks()
//							.hasLinked(source.getModel(), target.getModel());
					// 已经和原表创建过关系就不能和原表的快照发生关系,些逻辑被否
					// if (!hasLinked) {
						// 已经存在A——B 不能建立B——A
						if (!source.getReferedElementList().contains(target)) {
							// 不能重复建立A——B
							if (!source.getReferringElementList().contains(
									target)) {
								return true;
							}
						}
					//}
				}
			}
		}
		return false;
	}

	@Override
	protected void doExecute() {
		link = new Link(source, target);
		link.checkAndInit();
		this.link.getTarget().refreshTargetConnections();
		this.link.getSource().refreshSourceConnections();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	final public void redo() {
		try {
			link.reconnect();
			this.link.getTarget().refreshTargetConnections();
			this.link.getSource().refreshSourceConnections();
		} catch (Exception e) {
			Utils.showExceptionDialog(e);
		}
	}

	@Override
	protected void doUndo() {
		link.disconnect();
		this.link.getTarget().refreshTargetConnections();
		this.link.getSource().refreshSourceConnections();
	}

}
